package com.example.common.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final Long EXPIRE = 120 * 60 * 1000L;     // 有效期120分钟
    private static final String SECRET = "food";  // 秘钥


    /**
     * 生成Token
     * @param username 用户名
     * @return  token
     */
    public static String generateToken(String username) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + EXPIRE);
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        return Jwts.builder()
                .setHeaderParam("type", "JWT")
                .setClaims(map)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    /**
     * 解析token
     * @param token 待解析token
     * @return 解析值
     */
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * token 是否过期
     * @param token Token
     * @return  是否过期
     */
    public static boolean isExpire(String token) {
        try {
            Claims claims = JwtUtil.parseToken(token);
            return ObjectUtils.isEmpty(claims) || claims.getExpiration().before(new Date());
        }catch (Exception e) {
            return true;
        }
    }

    /**
     * 解析token获取用户名
     * @param token Token
     * @return 数据
     */
    public static Map<String, Object> getInfoFromToken(String token) {
        Map<String, Object> map = new HashMap<>();
        if(ObjectUtils.isEmpty(token)) {
            return map;
        }
        try {
            Jws<Claims> jws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
            Claims body = jws.getBody();
            Object username = body.get("username");
            Object authorityList = body.get("authorities");
            map.put("username", username);
            map.put("authorities", authorityList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static String oldOrNewToken(String token, String username) {
        long expirationTime = JwtUtil.parseToken(token).getExpiration().getTime();
        if(expirationTime - new Date().getTime() < 1000 * 60 * 5) {
            return JwtUtil.generateToken(username);
        }else {
            return token;
        }
    }
}
